//
//  DIVARequest.m
//  JigSawKiosk
//
//  Created by Stulberg on 10-10-20.
//  Copyright 2010 FruitonLabs. All rights reserved.
//

#import "DIVARequest.h"


extern float kDIVAtimeout ;
 
extern NSString* kDIVAip ;
extern NSString* kDIVAport ;
extern NSString* kDIVAusername ;
extern NSString* kDIVApassword ;
extern NSString* kDIVApresent ;
extern NSString* kDIVAabsent ;
 



@implementation DIVARequest

@synthesize responseData, requestString;

- (id) init {
	self = [super init] ;
	if (self) {
		
		responseData = [NSMutableData new];
		fLock = [NSRecursiveLock new];
		//requestString = [[NSString stringWithFormat:@"http://"] retain];
		//if (kUseDIVA == 1) {
		// http://192.168.1.55:49161/messaging/getMessage?destinationId=videokiosk&username=presentation&password=
		requestString = [NSString stringWithFormat:@"%@", @"http://"] ;
		requestString = [NSString stringWithFormat:@"%@%@", requestString, kDIVAip] ; // IP
		requestString = [NSString stringWithFormat:@"%@%@", requestString, @":"];
		requestString = [NSString stringWithFormat:@"%@%@", requestString, kDIVAport] ; // port
		requestString = [NSString stringWithFormat:@"%@%@", requestString, @"/messaging/getMessage?destinationId=videokiosk&username="] ;
		requestString = [NSString stringWithFormat:@"%@%@", requestString, kDIVAusername] ; // username
		requestString = [NSString stringWithFormat:@"%@%@", requestString, @"&password="] ;
		requestString = [NSString stringWithFormat:@"%@%@", requestString, kDIVApassword] ; // password
		[requestString retain] ;
		//} else {
		//requestString = [NSString stringWithFormat:@"%@", @"http://twitter.com/statuses/public_timeline.json"] ;
		//}
		
		request = [[NSURLRequest requestWithURL:[NSURL URLWithString:requestString]
									cachePolicy:NSURLRequestUseProtocolCachePolicy
								timeoutInterval:kDIVAtimeout] retain];
		
		[[NSURLConnection alloc] initWithRequest:request delegate:self];
		//[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
		
		parser = [[SBJsonParser alloc] init];
		
		
		//divaThread = [[NSThread alloc] init];
		//divaThread = [[NSThread alloc] initWithTarget:self selector:@selector(startTheBackgroundJob) object:nil];
		//[divaThread start] ;
		//[NSThread detachNewThreadSelector:@selector(startTheBackgroundJob) toTarget:self withObject:nil];  
		//[self startRequestTimer] ;
	}
	return self ;
}




-(void) dealloc {
	[parser release] ;
	[requestString release] ;
	[request release] ;
	[requestTimer release] ;
	[divaThread release];
	[pool release] ;
	[runloop release] ;
	[super dealloc] ;
}

/*
- (void)startTheBackgroundJob {  
	
    pool = [[NSAutoreleasePool alloc] init];  
	runloop = [NSRunLoop currentRunLoop] ;
    // wait for 3 seconds before starting the thread, you don't have to do that. This is just an example how to stop the NSThread for some time  
    [NSThread sleepForTimeInterval:5];  
    //[self performSelectorOnMainThread:@selector(divaRequestThreadjob) withObject:nil waitUntilDone:NO];  
	//[self performSelector:@selector(divaRequestThreadjob) onThread:divaThread withObject:nil waitUntilDone:NO] ;
	[NSTimer scheduledTimerWithTimeInterval: kBangDiva
									 target: self
								   selector: @selector(requestTimerMethod:)
								   userInfo: nil
									repeats: YES];
	[runloop run] ;
    [pool release];  
	
}  

 - (void)divaRequestThreadjob {  
 printf("svdljvsdbkjbkvjdfbkj");
 [self performSelectorOnMainThread:@selector(presentMethod) withObject:nil waitUntilDone:NO];
 [self jsonRequest] ;
 [NSTimer scheduledTimerWithTimeInterval:kBangDiva target:self selector:@selector(divaRequestThreadjob) userInfo:nil repeats:NO];  
 
 } 
 */
// our delegate methods

- (void)setDelegate:(id)aDelegate {
	// not retained
	delegate = aDelegate;
}

- (void)delegatedMethod {
	[delegate divaRequestCallback:self] ;
}

-(void) presentMethod {
	
	[delegate divaPresentCallback:self] ;
}


- (void) absentMethod {
	[delegate divaAbsentCallback:self] ;
}

//
//
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[fLock lock];
	//NSLog(@"didReceiveResponse") ;
	[responseData setLength:0];
	[fLock unlock];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[fLock lock];
	//NSLog(@"didReceiveData") ;
	[responseData appendData:data];
	[fLock unlock];
}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{	
	[fLock lock];
    // release the connection, and the data object
    [connection release];
	
    // inform the user
	/*
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
	*/
	[[NSURLConnection alloc] initWithRequest:request delegate:self]; // when time out start a new connection
	[fLock unlock];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	
	[fLock lock];
	//NSLog(@"connectionDidFinishLoading") ;
	[connection release];	
	/*
	 NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	 [responseData release];
	 request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestString]
	 cachePolicy:NSURLRequestUseProtocolCachePolicy
	 timeoutInterval:60.0];
	 [[NSURLConnection alloc] initWithRequest:request delegate:self];
	 */
	
	// Get JSON as a NSString from NSData response
	NSString *json_string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	// NSLog(@"JSON string = %@", json_string) ;
	
	// parse the JSON response into an object
	// Here we're using NSArray since we're parsing an array of JSON status objects
	NSArray *statuses = [parser objectWithString:json_string error:nil];
	
	NSDictionary *status = (NSDictionary*) statuses ;
	NSString *message = [[status objectForKey:@"data"] objectForKey:@"message"] ;
	
	
	//NSLog(@"%@", message) ;
	
	if ([message isEqual:kDIVApresent] ) {
		//[self presentMethod] ;
		[self performSelectorOnMainThread:@selector(presentMethod) withObject:nil waitUntilDone:NO]; 
	}
	
	if([message isEqual:kDIVAabsent]) {
		//[self absentMethod] ;
		[self performSelectorOnMainThread:@selector(absentMethod) withObject:nil waitUntilDone:NO]; 
	}
	
	[json_string release] ;
	
	[fLock unlock];
	
	[[NSURLConnection alloc] initWithRequest:request delegate:self];
	
	//[self newConnection] ;
}

/*
-(void) newConnection {
	request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestString]
							   cachePolicy:NSURLRequestUseProtocolCachePolicy
						   timeoutInterval:kDIVAtimeout] ;
	
	//response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	[[NSURLConnection alloc] initWithRequest:request delegate:self];	
}
//
//

-(void) startRequestTimer {
	requestTimer =  [NSTimer scheduledTimerWithTimeInterval: kBangDiva
													 target: self
												   selector: @selector(requestTimerMethod:)
												   userInfo: nil
													repeats: YES];
}


-(void)requestTimerMethod:(NSTimer*) timer {
	[self jsonRequest] ;
}

-(void) jsonRequest {
	// Create new SBJSON parser object
	
	//[[NSURLConnection alloc] initWithRequest:request delegate:self];
	
	//[self performSelectorOnMainThread:@selector(presentMethod) withObject:nil waitUntilDone:NO];
	//[self performSelectorOnMainThread:@selector(absentMethod) withObject:nil waitUntilDone:NO];
	
	
	 if(kDebug) NSLog(@"SENDING REQUEST") ;
	 
	 //NSString *requestString  ;
	 if (kUseDIVA == 1) {
	 // http://192.168.1.55:49161/messaging/getMessage?destinationId=videokiosk&username=presentation&password=
	 requestString = [NSString stringWithFormat:@"%@", @"http://"] ;
	 requestString = [NSString stringWithFormat:@"%@%@", requestString, kDIVAip] ; // IP
	 requestString = [NSString stringWithFormat:@"%@%@", requestString, @":"] ;
	 requestString = [NSString stringWithFormat:@"%@%@", requestString, kDIVAport] ; // port
	 requestString = [NSString stringWithFormat:@"%@%@", requestString, @"/messaging/getMessage?destinationId=videokiosk&username="] ;
	 requestString = [NSString stringWithFormat:@"%@%@", requestString, kDIVAusername] ; // username
	 requestString = [NSString stringWithFormat:@"%@%@", requestString, @"&password="] ;
	 requestString = [NSString stringWithFormat:@"%@%@", requestString, kDIVApassword] ; // password
	 
	 } else {
	 requestString = [NSString stringWithFormat:@"%@", @"http://twitter.com/statuses/public_timeline.json"] ;
	 }
	 
	 // Prepare URL request to download
	 request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestString] 
	 //cachePolicy:NSURLRequestUseProtocolCachePolicy
	 cachePolicy:NSURLRequestReloadIgnoringCacheData
	 timeoutInterval:5.0];
	 
	 // Perform request and get JSON back as a NSData object
	 NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	 
	 // Get JSON as a NSString from NSData response
	 NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
	 if(kDebug) NSLog(@"JSON string = %@", json_string) ;
	 
	 // parse the JSON response into an object
	 // Here we're using NSArray since we're parsing an array of JSON status objects
	 NSArray *statuses = [parser objectWithString:json_string error:nil];
	 
	 NSDictionary *status = (NSDictionary*) statuses ;
	 NSString *message = [[status objectForKey:@"data"] objectForKey:@"message"] ;
	 
	 
	 if(kDebug) NSLog(@"%@", message) ;
	 
	 if ([message isEqual:kDIVApresent] ) {
	 //[self presentMethod] ;
	 [self performSelectorOnMainThread:@selector(presentMethod) withObject:nil waitUntilDone:NO]; 
	 }
	 
	 if([message isEqual:kDIVAabsent]) {
	 //[self absentMethod] ;
	 [self performSelectorOnMainThread:@selector(absentMethod) withObject:nil waitUntilDone:NO]; 
	 }
	 
	 */
	// Each element in statuses is a single status
	// represented as a NSDictionary
	/*
	 for (NSDictionary *status in statuses)
	 {
	 // You can retrieve individual values using objectForKey on the status NSDictionary
	 // This will print the tweet and username to the console
	 if (kUseDIVA == 1) 
	 NSLog(@"%@", [[status objectForKey:@"data"] objectForKey:@"message"]);
	 else
	 NSLog(@"%@ - %@", [status objectForKey:@"text"], [[status objectForKey:@"user"] objectForKey:@"screen_name"]);
	 
	 }
	 
	//[json_string release] ;
	
}
*/
@end
